/* Andreas Baum
 * JBPClientConnector.java
 * Handles setting up the client proxy
 * CS 78 - Networks
 */

/* 
 * The notion of "server" in this project can lead to confusion: 
 * Indeed, it is employed with two separate meanings.
 * 1. The central login server
 * 2. The "server" side of the iTunes connection to which another proxy connect
 * , and which allows another user to access the user's iTunes library.
 */


package jbpClientConnector;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import com.apple.dnssd.DNSSDException;





/** Sets up the client proxy */
public class JBPClientConnector {

	public static int SERVICE_PORT = 0;
	public static int SERVER_PORT = 4444;

	private static Socket extSocket;
	private static String host;

	
	public JBPClientConnector(String hostname, String username) throws IOException {

		
		// Connect to the server proxy first:
		host = hostname;
		// System.out.println("Attempting to connect to " + host + "...");
		try {
			// send connection request:
			extSocket = new Socket(host, SERVER_PORT);
		} catch (UnknownHostException e) {
			// If host can't be found:
			System.err.println("ERROR: Don't know about host: " + host + ".");
			System.exit(1);
		} catch (IOException e) {
			// If host doesn't accept connections:
			System.err.println("ERROR: Couldn't get I/O for "
					+ "the connection to: " + host + ".");
			System.exit(1);
		}

		// connection is established, hand it over to a client thread.
		DataThread cExtThread = new DataThread(extSocket, "cExtThread");


		// Register iTunes service listener, and establish connection to iTunes:
		String serviceName = "_daap._tcp";
		String otherName = username;
		// the port is allocated by the system:
		ServerSocket serviceSocket = new ServerSocket(SERVICE_PORT);

		try
		{
			// Register the daap service:
			ServiceRegistrar iTunesRegistrar = new ServiceRegistrar(otherName, 
					serviceName, serviceSocket.getLocalPort());
			while (!iTunesRegistrar.isRegistered());
			// start a new thread on the socket as soon as iTunes sends
			// something back:
			DataThread serviceThread = new DataThread(serviceSocket.accept(), "iTunesServiceThread");
			// Tell the iTunes service thread and the external proxy thread to pipe things through
			// to each other:
			serviceThread.setOtherThread(cExtThread);
			cExtThread.setOtherThread(serviceThread);

		} catch (InterruptedException e) {
			System.err.println("InterruptedException: " + e);
		}
		catch (DNSSDException e){
			System.err.println("DNSSDException: " + e);
		}
		catch (IOException e) {
			System.out.println("Accept failed: " + serviceSocket.getLocalPort());
			System.exit(-1);
		}

	}

}